#include "stm32f10x.h"
#include "Encoder_Interface.h"

void init_encoder_interface(void){

    
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
    
    GPIO_Init(GPIOA,&(GPIO_InitTypeDef){
        
        .GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7,
        .GPIO_Mode = GPIO_Mode_IN_FLOATING,
        .GPIO_Speed=GPIO_Speed_50MHz
    });
    
    TIM_TimeBaseInit(TIM3,&(TIM_TimeBaseInitTypeDef){
    
        .TIM_Prescaler= 0x00, // 不进行预分频
        .TIM_CounterMode = TIM_CounterMode_Up, // 无效配置，计数器的行为被编码器接口接管
        .TIM_Period = 0xffff,       // 配置满量程计数
        .TIM_ClockDivision=TIM_CKD_DIV1
    
    });
    
    TIM_ICInitTypeDef TIM_ICInitStruct;
    TIM_ICStructInit(&TIM_ICInitStruct);
    TIM_ICInitStruct.TIM_Channel = TIM_Channel_1;
    TIM_ICInitStruct.TIM_ICFilter = 0xf;
    // 这里的极性选择实际控制的是电平是否反转
    // TIM_EncoderInterfaceConfig 中也会再次配置极性
    TIM_ICInitStruct.TIM_ICPolarity = TIM_ICPolarity_Rising;
    TIM_ICInit(TIM3,&TIM_ICInitStruct);
    
    TIM_ICInitStruct.TIM_Channel = TIM_Channel_2;
    TIM_ICInit(TIM3,&TIM_ICInitStruct);
    
    
    TIM_EncoderInterfaceConfig(
        TIM3,
        TIM_EncoderMode_TI12,
        TIM_ICPolarity_Rising,
        TIM_ICPolarity_Rising
    );
    
    TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE);
    
    NVIC_Init(&(NVIC_InitTypeDef){
    
        .NVIC_IRQChannel = TIM2_IRQn,
        .NVIC_IRQChannelPreemptionPriority=1,
        .NVIC_IRQChannelSubPriority=2,
        .NVIC_IRQChannelCmd= ENABLE
    
    });
    
    TIM_Cmd(TIM3,ENABLE);

}

